<script setup lang="ts">
import ToolBar from "./components/ToolBar.vue";
import {onMounted} from 'vue'
import {useFrame} from "./lib/frame.ts";
import {useFile} from "./lib/file.ts";
import {useHistory} from "./lib/history.ts";

// 不同的编辑器需要不同的实现开始
const EDITOR_IFRAME_URL = './editor/index.html?tldraweditor'
const EDITOR_DEFAULT_FILE_NAME = 'NewFile.tldraw.fad'
const EDITOR_FILE_TYPE = 'TldrawEditor'
const EDITOR_FILE_CONTENT = null

const {
    iframe,
    onIframeLoad,
    callIframe,
} = useFrame()
const {
    filePath,
    doOpen,
    doOpenNew,
    doOpenFile,
    doSave,
    fileInit,
} = useFile({
    EDITOR_DEFAULT_FILE_NAME,
    EDITOR_FILE_TYPE,
    EDITOR_FILE_CONTENT,
    callIframe,
})
const {
    fileHistories,
    historyInit,
} = useHistory({
    filePath
})
onMounted(async () => {
    await fileInit()
    await historyInit()
})
if (window.focusany) {
    focusany.onPluginReady((data) => {
        if (data.actionMatch?.name === 'editor') {
            if (data.actionMatchFiles && data.actionMatchFiles.length > 0) {
                doOpenFile(data.actionMatchFiles[0].path).then()
            }
        }
    })
    focusany.registerHotkey('save', () => {
        doSave()
    })
}

const blobToUintBuffer = async (blob: Blob) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = () => {
            resolve(new Uint8Array(reader.result as ArrayBuffer))
        }
        reader.onerror = reject
        reader.readAsArrayBuffer(blob)
    })
}
const doExport = async (type: string) => {
    let content = await callIframe('editorExport', type)
    const option = {
        isBase64: false,
    }
    content = await blobToUintBuffer(content as any)
    console.log('export', {type, content})
    focusany.util.save(`图片_${focusany.util.datetimeString()}.${type}`, content as any, option)
}
</script>

<template>
    <div class="flex border-t border-solid border-gray-300" style="height:100vh;">
        <div class="border-r border-solid border-gray-300 w-12 flex-shrink-0">
            <ToolBar
                :file-path="filePath"
                :file-histories="fileHistories"
                @open="doOpen"
                @openNew="doOpenNew"
                @save="doSave"
                @saveAs="doSave(true)"
                @open-file="doOpenFile"
                @export="doExport"
            />
        </div>
        <div class="flex-grow">
            <iframe
                ref="iframe"
                @load="onIframeLoad"
                style="width:100%;height:100%;border:none;"
                :src="EDITOR_IFRAME_URL"></iframe>
        </div>
    </div>
</template>
